字串可以用三種方式建立:
let text1 = "Hello World";  // 使用雙引號
let text2 = 'Hello World';  // 使用單引號
let text3 = `Hello World`;  // 使用反引號(模板字串)
建議:在一般情況下使用 單引號 ' 或 雙引號 ",
若需要插入變數或換行時,使用 反引號 `。
使用 .length 屬性可以取得字串長度:
let text = "Hello";
console.log(text.length);  // 輸出:5
可以使用 + 來合併字串:
let firstName = "John";
let lastName = "Doe";
let fullName = firstName + " " + lastName;
console.log(fullName);  // John Doe
或使用 模板字串 (Template Literals):
let fullName = `${firstName} ${lastName}`;
console.log(fullName);  // John Doe
| 方法 | 說明 | 範例 | 
|---|---|---|
| toUpperCase() | 轉為大寫 | "hello".toUpperCase()→"HELLO" | 
| toLowerCase() | 轉為小寫 | "HELLO".toLowerCase()→"hello" | 
| trim() | 移除前後空白 | "  hi  ".trim()→"hi" | 
| slice(start, end) | 擷取部分字串 | "Hello".slice(1, 4)→"ell" | 
| substring(start, end) | 擷取部分字串(不支援負數) | "Hello".substring(1, 4)→"ell" | 
| replace(old, new) | 替換內容 | "I like cats".replace("cats", "dogs")→"I like dogs" | 
| includes(value) | 檢查是否包含字串 | "Hello".includes("ell")→true | 
| indexOf(value) | 回傳字串出現的位置 | "Hello".indexOf("e")→1 | 
| split(separator) | 以特定分隔符切割字串 | "a,b,c".split(",")→["a", "b", "c"] | 
let name = "Sam";
let age = 25;
let message = `我的名字是 ${name},我今年 ${age} 歲。`;
console.log(message);
// 輸出:我的名字是 Sam,我今年 25 歲。
使用反引號 ` 可以建立多行字串:
let poem = `
Roses are red,
Violets are blue,
JavaScript is awesome,
And so are you!
`;
console.log(poem);
如果字串內需要引號,可以用 反斜線 \ 轉義:
let quote = "He said, \"JavaScript is fun!\"";
console.log(quote);
// 輸出:He said, "JavaScript is fun!"
let product = "Laptop";
let price = 32000;
let info = `商品名稱:${product}\n價格:${price} 元`;
console.log(info);
/*
輸出:
商品名稱:Laptop
價格:32000 元
*/
| 主題 | 說明 | 
|---|---|
| 字串建立 | 使用 ' '," ", 或` | 
| 字串長度 | .length | 
| 字串連接 | +或 模板字串${} | 
| 常見方法 | toUpperCase(),slice(),replace(),includes(),split() | 
| 多行字串 | 使用反引號 ` | 
| 跳脫字元 | 使用 \ |